package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.lzx.iteam.adapter.AttendanceCreateAdapter;
import com.lzx.iteam.bean.AttendanceData;
import com.lzx.iteam.net.*;
import com.lzx.iteam.util.AllDialogUtil;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.List;

import static com.lzx.iteam.MainActivity.mActivity;

/**
 * 考勤列表，新建考勤入口
 * Created by Megan on 16/4/11.
 */
public class AttendanceCreateActivity extends Activity implements View.OnClickListener,AttendanceCreateAdapter.AttendanceEditListener {

    private ListView mLvList;
    private ImageView mIvGuide;
    private LinearLayout mLlBack;
    private AttendanceCreateAdapter mAdapter;
    private LinearLayout mLlNew;
    private String mGroupId = "";
    private String mGroupName;
    private String mUserType;
    private String mContactId;
    private ArrayList<AttendanceData> attendanceDatas;


    private int mPosition;
    private int mShowGuide;

    private AllDialogUtil mDialogUtil;
    private PreferenceUtil mPreferenceUtil;
    private Dialog mWaitDialog;
    private final int GET_ATTENDANCE_LIST = 1000;
    private final int DEL_ATTENDANCE_MSG = 1001;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_ATTENDANCE_LIST:
                    if (msg.arg1 == 0) {
                        attendanceDatas = (ArrayList<AttendanceData>) msg.obj;
                        mAdapter.bindData(attendanceDatas);
                        mShowGuide = mPreferenceUtil.getInt("create_at_guide",0);
                        if (attendanceDatas.size() == 0 && mShowGuide == 0){
                            mIvGuide.setVisibility(View.VISIBLE);
                        }else{
                            mIvGuide.setVisibility(View.GONE);
                        }
                        mPreferenceUtil.save("create_at_guide",1);

                    } else {
                        Toast.makeText(AttendanceCreateActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
                case DEL_ATTENDANCE_MSG:
                    httpReqDlgDismiss();
                    if (msg.arg1 == 0) {
                        if (attendanceDatas.size() > mPosition) {
                            attendanceDatas.remove(mPosition);
                        }
                        if (mAdapter != null) {
                            mAdapter.bindData(attendanceDatas);
                        }
                    } else {
                        Toast.makeText(AttendanceCreateActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.attendance_create_layout);
        initView();
        getIntentData();
        getAttendanceList();
    }

    private void initView() {
        mDialogUtil = AllDialogUtil.getInstance(this);
        mPreferenceUtil = PreferenceUtil.getInstance(this);

        mLvList = (ListView) findViewById(R.id.lv_attendance_create_list);
        mLlBack = (LinearLayout) findViewById(R.id.ll_attendance_create_back);
        View view = LayoutInflater.from(this).inflate(R.layout.attendance_create_footer, null);
        mLlNew = (LinearLayout) view.findViewById(R.id.ll_attendance_create_new);
        mIvGuide = (ImageView) findViewById(R.id.iv_create_hand_guide);

        mLvList.addFooterView(view);
        mAdapter = new AttendanceCreateAdapter(this);
        mAdapter.setEditListener(this);
        mLvList.setAdapter(mAdapter);
        mLlBack.setOnClickListener(this);
        mLlNew.setOnClickListener(this);
        /*mLvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(AttendanceCreateActivity.this, AttendanceSettingActivity.class);
                AttendanceData attendanceData = attendanceDatas.get(i);
                attendanceData.setGroupId(mGroupId);
                attendanceData.setGroupName(mGroupName);
                intent.putExtra("attendanceData", attendanceData);
                intent.putExtra("group_name", mGroupName);
                intent.putExtra("user_type", mUserType);
                intent.putExtra("contact_id", mContactId);
                startActivity(intent);
            }
        });*/

        mLvList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                mPosition = i;
                showDeleteAttendanceDlg(attendanceDatas.get(i).get_id());
                return true;
            }
        });
    }

    private void getIntentData() {
        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mGroupName = intent.getStringExtra("group_name");
        mUserType = intent.getStringExtra("user_type");
        mContactId = intent.getStringExtra("contact_id");
    }

    /**
     * 考勤点列表
     */
    private void getAttendanceList() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        GetAttendanceList getAttendanceList = new GetAttendanceList(mHandler.obtainMessage(GET_ATTENDANCE_LIST), this);
        getAttendanceList.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_LIST;
        getAttendanceList.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(getAttendanceList);

    }


    /**
     * 删除考勤点
     */
    private void delAttendance(String id) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_FORM_ID, id));
        GetMsgHttpReceiver getMsgHttpReceiver = new GetMsgHttpReceiver(mHandler.obtainMessage(DEL_ATTENDANCE_MSG));
        getMsgHttpReceiver.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_DEL;
        getMsgHttpReceiver.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(getMsgHttpReceiver);

    }

    /**
     * 退出或解散群组
     */
    public void showDeleteAttendanceDlg(final String id) {

        String okText = this.getString(R.string.label_btn_delete);
        String cancelText = this.getString(R.string.cancel);
        mDialogUtil.titleDeleteMsgStyle(okText, cancelText, "删除该考勤点？");
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                httpReqDlgShow();
                delAttendance(id);
                lDialog.dismiss();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_attendance_create_back:
                if ("yes".equals(mPreferenceUtil.getString("isLogin", ""))) {
                    Intent intent = new Intent(AttendanceCreateActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    finish();
                }
                break;
            case R.id.ll_attendance_create_new:
                AttendanceData attendanceData = new AttendanceData();
                attendanceData.setGroupId(mGroupId);
                attendanceData.setGroupName(mGroupName);
                Intent intent = new Intent(AttendanceCreateActivity.this, BaiduMapActivity.class);
                intent.putExtra("attendanceData", attendanceData);
                intent.putExtra("group_name", mGroupName);
                intent.putExtra("user_type", mUserType);
                intent.putExtra("contact_id", mContactId);
                startActivity(intent);
                break;
        }
    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = AllDialogUtil.getInstance(this).waitDialog();
//            mProgressDialog.setCancelable(false);
            mWaitDialog.show();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if ("yes".equals(mPreferenceUtil.getString("isLogin", ""))) {
                    Intent intent = new Intent(AttendanceCreateActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                } else {
                    finish();
                    break;
                }
        }

        return true;

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    @Override
    protected void onStop() {
        mIvGuide.setVisibility(View.GONE);
        super.onStop();
    }

    @Override
    public void editRule(AttendanceData attendanceData) {
        Intent intent = new Intent(AttendanceCreateActivity.this, AttendanceSettingActivity.class);
        attendanceData.setGroupId(mGroupId);
        attendanceData.setGroupName(mGroupName);
        intent.putExtra("attendanceData", attendanceData);
        intent.putExtra("group_name", mGroupName);
        intent.putExtra("user_type", mUserType);
        intent.putExtra("contact_id", mContactId);
        startActivity(intent);
    }

    @Override
    public void editSubClass(AttendanceData attendanceData) {
        Intent sub = new Intent(AttendanceCreateActivity.this,AttendanceSubClassExcleActivity.class);
        sub.putExtra("group_id", mGroupId);
        sub.putExtra("form_id", attendanceData.get_id());
        sub.putExtra("group_name", mGroupName);
        sub.putExtra("user_type", mUserType);
        sub.putExtra("contact_id", mContactId);
        sub.putExtra("sub_class",attendanceData.getSubForms());
        startActivity(sub);

    }
}
